﻿using System.Linq;
using System.Web.Mvc;
using MethodWorx.CMS.Content;
using MethodWorx.CMS.Services;
using MethodWorx.CMS.UI.Application.ActionResults;
using MethodWorx.Core.DomainModel;
using MethodWorx.CMS.UI.Application;
using System;
using System.Collections.Generic;
using MethodWorx.CMS.TemplateParser;

namespace MethodWorx.CMS.UI.Areas.Application.Controllers
{
    public class PublishPageController : ApplicationController
    {
        private ContentService contentService;
        private IUnitOfWorkFactory unitOfWorkFactory;
        //
        // GET: /Application/Page/
        public PublishPageController(ContentService contentService, IUnitOfWorkFactory unitOfWorkFactory)
        {
            this.contentService = contentService;
            this.unitOfWorkFactory = unitOfWorkFactory;
        }

        [HttpGet]
        public ActionResult PublishOptions(Page id)
        {
            if(id == null)
                throw new WebException("Page Not Found");

            return View(id);
        }

        [HttpPost]
        public ActionResult PublishOptions(Page id, Guid [] children, string submit)
        {
            switch ((submit ?? "").ToLower())
            {
                case "publish":
                    if (id == null)
                        throw new WebException("Page Not Found");

                    try
                    {
                        List<Guid> all = new List<Guid>();
                        all.Add(id.Id);
                        if(children != null)
                            all.AddRange(children);
                        //
                        //  else gor it);
                        using (var uow = this.unitOfWorkFactory.Begin())
                        {
                            contentService.PublishPages(all.ToArray());

                            uow.Commit();
                        }
                        this.ViewData["message"] = "Page(s) where successfully published";
                    }
                    catch(BusinessRuleException bre)
                    {
                        this.ViewData["error"] = bre.Message;
                    }
                    catch (TemplateParsingException pte)
                    {
                        this.ViewData["error"] = "Error Compiling Template: " + pte.Message;
                    }

                    

                    return View(id);
                    break;
                default:
                    return new CloseDialogResult();
            }
        }
    }
}
